package cn.ztf.zshop.sys.service.impl;

import cn.ztf.zshop.security.admin.dto.PermissionDto;
import cn.ztf.zshop.security.admin.service.SysUserSecurityService;
import cn.ztf.zshop.sys.dao.SysMenuDao;
import cn.ztf.zshop.sys.dao.SysRoleDao;
import cn.ztf.zshop.sys.dao.SysUserDao;
import cn.ztf.zshop.sys.po.Menu;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class SysUserSecurityServiceImpl implements SysUserSecurityService {

    private final SysUserDao sysUserDao;
    private final SysRoleDao sysRoleDao;

    private final SysMenuDao sysMenuDao;

    @Override
    public List<String> findPermissionByRoleId(String roleId) {
        return sysUserDao.findPermissionByRoleId(roleId);
    }

    @Override
    public List<String> findRoleByUserId(Object loginId) {
        return sysRoleDao.findRoleByUserId(Long.parseLong((String) loginId))
                .stream()
                .map(String::valueOf)
                .collect(Collectors.toList());
    }

    @Override
    public List<PermissionDto> findAllPermission() {
        List<Menu> menus =  sysMenuDao.findAllPermission();
        return menus.stream()
                .filter(menu -> StringUtils.hasLength(menu.getPerms()) && StringUtils.hasLength(menu.getUrl()) && StringUtils.hasLength(menu.getMethod()))
                .map(menu -> {
            PermissionDto permissionDto = new PermissionDto();
            permissionDto.setUrl(menu.getUrl());
            permissionDto.setMethod(menu.getMethod());
            permissionDto.setPermission(menu.getPerms().split(","));
            return permissionDto;
        }).collect(Collectors.toList());
    }
}
